//
//  ToolBar.swift
//  ZJTools
//
//  Created by 万孟超 on 2023/11/25.
//

import Cocoa

class ToolBar {
    
    var barItem: NSStatusItem?
    var eventMonitor: Any?
    init() { }
    
    func initBar() {
        barItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.squareLength))
        let menu = NSMenu()
        let item0 = menu.addItem(withTitle: "打开APP", action: #selector(menuItemSelected(_:)), keyEquivalent: "")
        menu.addItem(.separator())
        let item1 = menu.addItem(withTitle: "Xcode一键清理", action: #selector(menuItemSelected(_:)), keyEquivalent: "")
        menu.addItem(.separator())
        let item2 = menu.addItem(withTitle: "退出", action: #selector(menuItemSelected(_:)), keyEquivalent: "")
        item0.tag = 0
//        let barIcon = NSImage(named: "barIcon")
//        barIcon?.size = NSMakeSize(20, 20)
//        item0.image = barIcon
        item0.isEnabled = true
        item0.target = self
        
        item1.tag = 1
//        let cleanIcon = NSImage(named: "cleanIcon")
//        cleanIcon?.size = NSMakeSize(20, 20)
//        item1.image = cleanIcon
        item1.isEnabled = true
        item1.target = self
        
        item2.tag = 2
//        let barQuit = NSImage(named: "barQuit")
//        barQuit?.size = NSMakeSize(20, 20)
//        item2.image = barQuit
        item2.isEnabled = true
        item2.target = self
        barItem?.menu = menu
        
        let image = NSImage(named: "barIcon")
        image?.size = NSMakeSize(23, 23)
        barItem?.button?.image = image

    }
    
    lazy var currentVC = XcodeCleanBarVC(size: NSSize(width: 50, height: 50))
    
    lazy var popover: NSPopover = {
        let popover = NSPopover()
        popover.contentViewController = currentVC
        return popover
    }()
    
    func popoverShow() {
        if let button = barItem?.button {
            if popover.isShown {
                popover.performClose(nil)
            } else {
                popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
            }
        }
    }
    
    func setup() {
        initBar()
        eventMonitor = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { [weak self] event in
            self?.handleGlobalMouseDown(event)
        }
    }
    
    func handleGlobalMouseDown(_ event: NSEvent) {
        // 判断点击事件是否在您的主视图外部，如果是，则关闭 popover
        closePopover()
    }
    
    func closePopover() {
        Async(.main) {[self] in
            if popover.isShown {
                popover.performClose(nil)
            }
        }
    }
    
    @objc func menuItemSelected(_ sender: NSMenuItem) {
        // 处理菜单项的选择事件
        if sender.tag == 0 {
            AppDelegate.instance.mainWindowController.showWindow(nil)
        }else if sender.tag == 1 {
            popoverShow()
        }else if sender.tag == 2 {
            NSApplication.shared.terminate(nil)
        }
    }
    
}
